package com.jjapp.module.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jjapp.db.Database;
import com.jjapp.model.User;

public class LoginController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void init() throws ServletException {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Connection conn = Database.getDBConnection();
		PreparedStatement pstmt;
		PrintWriter out = response.getWriter();
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		System.out.println(email);
		System.out.println(password);
		try {
			String sql;
			sql = "SELECT id, email, password, created FROM m_user where email=? and password=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, email);
			pstmt.setString(2, password);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()){
				List<User> userList = new ArrayList<User>();
				sql = "SELECT id, email, password, created FROM m_user";
				pstmt = conn.prepareStatement(sql);
				ResultSet rs1 = pstmt.executeQuery();
				while(rs1.next()){
					User user = new User();
					user.setId(rs1.getInt("id"));
					user.setEmail(rs1.getString("email"));
					user.setCreated(rs1.getDate("created"));
					userList.add(user);
				}
				System.out.println(userList.size());
				request.setAttribute("userList", userList);
		        request.getRequestDispatcher("jsp/user.jsp").forward(request, response);
		     }else{
		    	 request.setAttribute("message", "Invalid Login");
		         request.getRequestDispatcher("/index.jsp").forward(request, response);
		     }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(conn !=null)
			{
				try {
					System.out.println("Connection Closed");
					conn.close();
				} catch (SQLException e) {
					System.out.println("Connection not Closed in catch");
					e.printStackTrace();
				}
			}else{
				System.out.println("Connection not Closed");
			}
		}
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		doGet(request, response);
	}

	public void destroy() {
		// do nothing.
	}

}
